<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmUserType;
use Doraemon\model\Creator\AreaAuthRecord;
use Doraemon\model\Creator\AreaAuthRecord as mAreaAuthRecord;
use Doraemon\model\Member;
use Doraemon\service\AdmBlank\FilterConfig;
use Doraemon\service\Creator\UserLevel3;
use Doraemon\service\Creators\AuditApply;
use Doraemon\service\User;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\Es\Photo;


class AreaAuditController extends Controller
{

    private $apply_status = [
        mAreaAuthRecord::APPLY_STATUS_WAIT => '未处理',
        mAreaAuthRecord::APPLY_STATUS_OK => '已通过',
        mAreaAuthRecord::APPLY_STATUS_NOT => '已驳回',
    ];

    private $fail_status = [
        mAreaAuthRecord::APPLY_STATUS_FAILURE => '失效',
        mAreaAuthRecord::APPLY_STATUS_EXPIRE => '过期',
    ];



    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = 'MCN';

        $tab->add($title, $this->applyListData($request));

        return $content
            ->header('领域认证申请列表')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }


    private function applyListData(Request $request)
    {
        $page = $request->input('page', 1);

        $pageSize = $request->input('per_page', 10);

        $search = $request->input('search', []);
        $query = [];
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query['uid'] = $search['uid'];
        }
        if (!empty($search['type'])) {
            $query['type'] = $search['type'];
        }

        if (isset($search['status'])) {
            $query['status'] = $search['status'];
        } else {
            $query['status'] = array_keys($this->apply_status);
        }

        $applyList = $this->getAreaRecordList($query, $page, $pageSize);

        $list = $this->formatList($applyList['data']);

        $gridModel = new pGridDataModel($list, $applyList['total'], ['perPage' => $pageSize, '']);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->paginate($gridModel->getPerPage());

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(4, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                    $filter->in('search.status', "状态")->select($this->apply_status)->default($search['status']);
                });

                $filter->column(4, function (Grid\Filter $filter) use ($search) {
                    $filter->in('search.type', '申请领域')->select(AuditApply::ADMIN_AREA_TYPE_TITLE)->default($search['type']);
                });


                //条件展开
                if ($search) $filter->expand();
            });

            $grid->column('id');
            $grid->column('uid', 'uid');
            $grid->column('nick', '昵称');
            $grid->column('level', '创作者等级');
            $grid->column('quality', '创作者质量');
            $grid->column('type', '所属领域')->using(AuditApply::ADMIN_AREA_TYPE_TITLE);
            $grid->column('action_num', '近90天互动数（点赞+评论+收藏）');
            $grid->column('content_nums', '近90天发布内容数｜精选内容数')->display(function (){
                return  $this->content_count. "|" .$this->star_count;
            });
            $grid->column('status', '状态')->using($this->apply_status);

            $grid->actions(function ($actions) {

                if ($actions->row->status == mAreaAuthRecord::APPLY_STATUS_WAIT) {
                    $actions->prepend('<p><a href="/admin/creators/apply/index/set/' . $actions->row->id . '/'.mAreaAuthRecord::APPLY_STATUS_NOT.'" >驳回</a></p>');
                    $actions->prepend('<p><a href="/admin/creators/apply/index/set/' . $actions->row->id . '/'.mAreaAuthRecord::APPLY_STATUS_OK.'" >通过</a></p>');
                }

                $actions->disableEdit();
                $actions->disableView();
                $actions->disableDelete();
            });
        });

        return $listGrid->render();
    }

    public function userList(Request $request, Content $content)
    {
        $tab = new tab();
        $title = 'MCN';

        $tab->add($title, $this->listData($request));

        return $content
            ->header('领域用户列表')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }

    public function failList(Request $request, Content $content)
    {
        $tab = new tab();
        $title = 'MCN';

        $tab->add($title, $this->listData($request, 2));

        return $content
            ->header('认证失败/失效用户列表')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }


    private function listData(Request $request, $admType = 1)
    {
        $page = $request->input('page', 1);

        $pageSize = $request->input('per_page', 10);

        $search = $request->input('search', []);
        $query = [];
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query['uid'] = $search['uid'];
        }

        if (!empty($search['type'])) {
            $query['type'] = $search['type'];
        }

        if ($admType == 1) {
            $query['status'] = AreaAuthRecord::APPLY_STATUS_OK;
        } else {
            if (!empty($search['status'])) {
                $query['status'] = $search['status'];
            } else {
                $query['status'] = array_keys($this->fail_status);
            }
        }



        $applyList = $this->getAreaRecordList($query, $page, $pageSize);

//        $list = $this->formatList($applyList);

        $gridModel = new pGridDataModel($applyList['data'], $applyList['total'], ['perPage' => $pageSize, '']);
//
//        $gridModel->setKeyType('string');
//        $gridModel->setKeyName("new_id");
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search, $admType) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->paginate($gridModel->getPerPage());

            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search, $admType) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(4, function (Grid\Filter $filter) use ($search, $admType) {
                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                    if ($admType == 2) {
                        $filter->in('search.status', "状态")->select($this->fail_status)->default($search['status']);
                    }
                });

                $filter->column(4, function (Grid\Filter $filter) use ($search) {
                    $filter->in('search.type', '申请领域')->select(AuditApply::ADMIN_AREA_TYPE_TITLE)->default($search['type']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->column('id');
            $grid->column('uid', 'uid');
            $grid->column('nick', '昵称')->display(function () {
                return Member::getNickByUid($this->uid);
            });

            $grid->column('level', '创作者等级')->display(function () {
                return  UserLevel3::getLevelInfoByUid($this->uid)['user_level_name'] ?? '';
            });

            $grid->column('type', '所属领域')->using(AuditApply::ADMIN_AREA_TYPE_TITLE);
            if ($admType == 1) {
                $grid->column('audit_time', '审核通过时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->audit_time);
                });
            } else {
                $grid->column('status', '状态')->using($this->fail_status);
                $grid->column('audit_time', '失效/过期时间')->display(function () {
                    if ($this->status == AreaAuthRecord::APPLY_STATUS_FAILURE) {
                        return date("Y-m-d H:i:s", $this->failure_time);
                    } else {
                        return date("Y-m-d H:i:s", $this->expire_time);
                    }
                });
            }
        });

        return $listGrid->render();
    }

    private function getAreaRecordList($query, $page, $pageSize)
    {
        $data = [
            "data" => [],
            "total" => 0
        ];

        $where = [
          "AND" => $query,
          "ORDER" => ['add_time' => "DESC"],
          "LIMIT" => [($page - 1)*$pageSize, $pageSize]
        ];

        $list = mAreaAuthRecord::select('*', $where);

        $count = mAreaAuthRecord::count($query);

        if ($list && is_array($list)){
            $data = [
                "total" => $count,
                "data" => $list
            ];
        }
        return $data;
    }

    public function formatList($list)
    {
        if (empty($list)) {
            return [];
        }
        $userIds = array_column($list, 'uid');
        $users = User::getUsersV2($userIds);
        $userAdmTags = AdmUserType::getByUids($userIds);

        $admQuality = FilterConfig::QUALITY;

        $relatedCateGory = AuditApply::getSecondCategoryId();
        $relatedCateGory = array_column($relatedCateGory, null, 'type');

        foreach ($list as &$val) {
            $val['nick'] = $users[$val['uid']]['nick'] ?? '';
            $userAdmTag = $userAdmTags[$val['uid']]['quality'] ?? 0;
            $val['quality'] = $admQuality[$userAdmTag];
            $val['level']  = UserLevel3::getLevelInfoByUid($val['uid'])['user_level_name'] ?? '';

            $typeRelated = $relatedCateGory[$val['type']] ?? [];

            $startTime = strtotime("-90 day", $val['add_time']);

            $where = [
                'uid' => $val['uid'],
                'type' => [0, 6],
                'category_second_id' => $typeRelated['second_ids'],
                'addtime[>]' => $startTime,
            ];
            $esResult = Photo::getNoteListByParams($where);
            $val['star_count'] = 0;
            $val['action_num'] = 0;
            $rows =  $esResult['rows'] ?? [];
            $val['content_count'] = count($rows);

            if (empty($rows)) {
                continue;
            }

            foreach ($rows as $item) {
                if ($item['admin_score'] >= 80) {
                    $val['star_count'] += 1;
                }
                $actionNum = $item['like'] + $item['comment'] + $item['favorite'];
                $val['action_num'] += $actionNum;
            }

        }

        return $list;
    }

    public function setStaus($id, $status)
    {
        if (!in_array($status, [mAreaAuthRecord::APPLY_STATUS_OK, mAreaAuthRecord::APPLY_STATUS_NOT])) {
            $error = new MessageBag([
                'title' => '审核失败'
            ]);
            return back()->with(compact('error'));
        }

        $info = mAreaAuthRecord::get('*', ['id' => $id]);

        if (empty($info)) {
            $error = new MessageBag([
                'title' => '审核失败，记录不存在'
            ]);
            return back()->with(compact('error'));
        }
        $time = time();
        $data['status'] = $status;
        $data['admin_id'] = Admin::user()->id ?? 0;
        $data['edit_time'] = $time;
//        dd($data);
//        $rs = DbCommentActivity::update($data, ['id' => $id]);

        if ($status == mAreaAuthRecord::APPLY_STATUS_OK) {
            $data['audit_time'] = $time;
            $data['month_check_time'] = $time;
            $data['expire_time'] = strtotime('+1 year', $time);
        }
        $rs = mAreaAuthRecord::update($data, ['id' => $id]);

        if ($rs) {
            if ($status == mAreaAuthRecord::APPLY_STATUS_OK) { //发送通过下行
               $typeName = AuditApply::ADMIN_AREA_TYPE_TITLE[$info['type']] ?? '';
               $msg = "恭喜你，你已通过领域认证，成为「{$typeName}优质创作者」，请再接再厉，持续在此领域下帮助其他住友吧！次月开始，每自然月内容发布数量大于等于1篇，可有效展示1年。";
//               $img = "https://img.haohaozhu.cn/Op-imageShow/6b1fb20ku0af03g00rxnv3x?iv=1";
               $img = "https://img.haohaozhu.cn/Op-imageShow/117c630ku0af0pz00ry4x82?iv=1";
               AuditApply::pushCheckResult($info['uid'], $msg, "", $img);
            }

            if ($status == mAreaAuthRecord::APPLY_STATUS_NOT) { //发送驳回下行
                $typeName = AuditApply::ADMIN_AREA_TYPE_TITLE[$info['type']] ?? '';
                $msg = "很遗憾，你未通过「{$typeName}优质创作者」申请。选择一个你擅长的领域，优化内容质量吧！14天后满足申请条件可再次申请。";
                $url = Hhzurl::getDomain() . '/community/field-auth/authenticate?type='.$info['type']; //二级页
                AuditApply::pushCheckResult($info['uid'], $msg, $url);
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            sleep(1);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }
}